package com.yztctech.a14_01_contentresolver;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

/**
 * ContentResolver的使用:内容解析者(先看ContentProvider端的代码)
 * 1 创建ContentResolver： getContentResolver();
 * 2 创建Uri
 * 3 执行响应的方法：insert，delete，一旦执行数据的操作方法，对于ContentProvider端就会触发相应方法
 * 备注:
 * 1.resolver端比较简单,只要访问uri就好,大部分是通过contentResolver进行增删改查的逻辑操作
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    //Uri常量
    //权威Authority：一般使用包名+类名的格式，全部是小写
    public static final String AUTHORITY = "com.yztctech.a14_01_customprovider.customprovider";
    //表名
    public static final String PATH_STUDENT = "student";
    public static final String PATH_STUDENT_ITME = "student/#"; //通配符：*所有字符，#所有数字
    //字段的名字;表中的字段名只在resolver端显示
    public static final String KEY_NAME = "name";
    public static final String KEY_AGE = "age";

    //定义全局的ContentResolver
    private ContentResolver contentResolver;

    //学生表的Uri
    private Uri studentUri;

    //测试的Count
    private int count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_insert).setOnClickListener(this);
        findViewById(R.id.btn_query).setOnClickListener(this);

        //初始化ContentResolver
        contentResolver = getContentResolver();

        //拼接Uri的地址
        String uriStr = "content://" + AUTHORITY + "/" + PATH_STUDENT;
        //创建Uri的对象
        studentUri = Uri.parse(uriStr);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_insert://增
                //通知ContentProvider插入数据
                ContentValues cv = new ContentValues();
                count++;
                cv.put(KEY_NAME, "Name" + count);
                cv.put(KEY_AGE, count);
                contentResolver.insert(studentUri, cv);
                break;
            case R.id.btn_query://查
                break;
        }
    }


}
